<template>
  <div>
    <nav class="top-nav">
      <div class="current-route">
        <span style="font-weight: 400;color: #606266">{{ mainTitle }}</span>
        <span style="margin-left: 10px;font-weight: 700;color: #c0c4cc;">></span>
        <span style="margin-left: 10px;font-weight: 400;color: #606266">{{ currentPageTitle }}</span>
      </div>
      <div class="container">
        <i class="el-icon-full-screen is-fullscreen" @click="toggleFullScreen()"></i>
        <i class="el-icon-refresh-right is-refresh" @click=" refreshCurrentRoute(reLoading)"></i>
        <el-dropdown @command="handleCommand">
          <span class="el-dropdown-link">
            {{ userName }}<i class="el-icon-arrow-down el-icon--right"></i>
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="b">退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </nav>
    <div>
      <ul id="children-bar" class="nav-items">
        <li v-for="(tag, index) in selectedTags" :key="index" @click="navigateTo(tag.name)"
            :class="{ 'active': tag.name === activeTag }" :style="tag.title === '首页' ? { padding: '0 20px' } : {}">
          {{ tag.title }}
          <button v-if="tag.title!=='首页'" @click.stop="removeTag(index)"  style="padding: 0">×</button>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>

import screenfull from'screenfull';

export default {
  data() {
    return {
      mainTitle: '大标题一', // 设置默认的大标题
      currentPageTitle: '首页', // 设置默认的当前页面标题
      selectedTags: [], // 记录已选择的子菜单标签
      allRoutes: [], // 存储所有的路由配置信息
      activeTag: null, // 用于存储当前激活的标签名
      reLoading:true,
     visitedTags: [], // 记录访问过的标签顺序
      userName: ''
    };
  },
  methods: {
    navigateTo(name) {
      if (this.$route.name !== name) {
        this.$router.push({name: name});
        this.addTagIfNotExists(this.$route.meta.title, this.$route.name, this.$route.path);
        this.updateVisitedTags(name); // 更新访问历史
      }
    },
    updateVisitedTags(name) {
      const index = this.visitedTags.indexOf(name);
      if (index > -1) {
        this.visitedTags.splice(index, 1);
      }
      this.visitedTags.push(name);
    },
    findTagByName(name) {
      return this.selectedTags.find(tag => tag.name === name);
    },

    addTagIfNotExists(title, name, path) {
      if (title!=='首页'){
        const tagExists = this.selectedTags.some(tag =>
            tag.title === title && !tag.fixed // 排除固定标签
        );
        if (!tagExists) {
          this.selectedTags.push({ title, name, path });
        }
      }

    },
    removeTag(index) {
      const tag = this.selectedTags[index];
      // 检查标签是否固定
      if (tag.fixed) {
        return;
      }

      this.selectedTags.splice(index, 1);

      // 如果关闭的是当前激活的标签
      if (tag.name === this.activeTag) {
        let lastIndex = this.visitedTags.indexOf(tag.name);
        if (lastIndex > -1) {
          this.visitedTags.splice(lastIndex, 1);
        }

        // 寻找前一个标签
        const previousTag = this.visitedTags.length ? this.findTagByName(this.visitedTags[this.visitedTags.length - 1]) : null;
        if (previousTag) {
          this.navigateTo(previousTag.name);
        } else {
          // 如果没有前一个标签，则可以默认跳转到首页或其他指定页面
          this.navigateTo('homeOne');
        }
      }
    },
    updateRouteInfo() {
      const to = this.$route;
      this.currentPageTitle = to.meta.title || '未知页面';

      const routeConfig = this.findRouteConfig(to.path);
      this.mainTitle = routeConfig ? routeConfig.meta.title : '未知大标题';

      const currentRoute = this.findChildRouteByPath(to.path);
      if (currentRoute) {
        this.addTagIfNotExists(currentRoute.meta.title, currentRoute.name, currentRoute.path);
        // 更新当前激活的标签
        this.activeTag = currentRoute.name;
      }
    },
    findRouteConfig(path) {
      function search(routes, parentPath = '') {
        let topRouteWithAlwaysShow = null;

        for (const route of routes) {
          // 构建完整的路径，确保总是以斜杠开始
          const fullPath =(parentPath + route.path).replace(/\/+/g, '/');
          // 如果当前路径是顶级路由并且带有 alwaysShow 属性，则记录此路由
          if (route.alwaysShow && path.startsWith(fullPath)) {
            topRouteWithAlwaysShow = route;
          }

          // 如果有子路由并且路径以当前路由路径开头，则递归搜索子路由
          if (route.children && path.startsWith(fullPath)) {
            const result = search(route.children, fullPath);
            if (result) return result; // 返回更精确匹配的子路由或顶级路由
          }

          // 如果路径完全匹配当前路由，但没有子路由，也应返回该路由
          if (path === fullPath) {
            return route;
          }
        }

        // 如果没有找到更具体的匹配项，则返回最匹配的带有 alwaysShow 的顶级路由（如果有）
        return topRouteWithAlwaysShow;
      }

      return search(this.allRoutes);
    },
    findChildRouteByPath(path) {
      function search(routes, parentPath = '') {
        for (const route of routes) {
          const fullPath = parentPath + route.path;

          // 如果路径完全匹配，则返回该路由对象
          if (path === fullPath) {
            return route;
          }

          // 如果有子路由，则递归搜索子路由
          if (route.children) {
            const result = search(route.children, fullPath + '/');
            if (result) return result;
          }
        }
        return null;
      }
      return search(this.allRoutes);
    },
    //全屏放大效果
    toggleFullScreen() {
      if (screenfull.isEnabled) {
        screenfull.toggle();
      }
    },
    //刷新当前路由
    refreshCurrentRoute(reLoading) {
      const resh = reLoading;
     this.$emit('childData', resh);
    },

    initializeTags() {
      const homeRoute = this.findChildRouteByName('homeOne');
      if (homeRoute) {
        this.selectedTags.push({
          title: homeRoute.meta.title,
          name: homeRoute.name,
          path: homeRoute.path,
          fixed: true // 添加一个属性标识是否固定
        });
        this.activeTag = homeRoute.name; // 设置默认激活标签为首页
        this.visitedTags.push(homeRoute.name); // 初始化访问历史
      }
    },
    findChildRouteByName(name) {
      function search(routes) {
        for (const route of routes) {
          if (route.name === name) return route;
          if (route.children) {
            const result = search(route.children);
            if (result) return result;
          }
        }
        return null;
      }
      return search(this.allRoutes);
    },
    async topName() {
      // const response = await topName();
      // const res = response.data;
      // if (res.code === 20000){
      //   this.userName = res.data;
      //   alert(this.userName)
      // }else {
      //   this.userName = '用户信息错误'
      // }

      this.userName = 'gyy';
    },

    async handleCommand(command) {
      // if (command === 'b'){
      //   const response = await loginOut();
      //   const res = response.data;
      //   if (res.code === 20000){
      //     this.$message.success("已退出登录");
      //     setTimeout(() => {
      //       this.$router.push({path: '/'});
      //     }, 200);
      //   }
      // }
      if (command === 'b'){
        await this.$router.push({path: '/'})
      }

    }

  },
  watch: {
    '$route': 'updateRouteInfo'
  },
  created() {
    // 初始化所有路由配置信息
    this.allRoutes = this.$router.options.routes;

    // 初始化标签
    this.initializeTags();

    // 在组件创建时立即更新路由信息
    this.updateRouteInfo();

    this.topName();
  }
};
</script>

<style scoped>
/* 保持样式不变 */
.top-nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0px 20px;
  background-color: #ffffff;
  border-bottom: 1px solid #ddd;
  height: 60px;
}

.nav-items {
  display: flex;
  align-items: center; /* 确保这一行存在 */
  gap: 8px;
  height: 55px;
  padding: 0px 20px;
  margin: 0;
}

.nav-items li {
  list-style: none;
  background-color: #ffffff;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  padding: 0 20px; /* 默认内边距 */
  height: 30px;
  border: 1px solid #cbcbcb;
  transition: border-color 0.3s ease, color 0.3s ease, padding 0.3s ease;
  box-sizing: border-box;
  position: relative; /* 添加相对定位 */
}

.nav-items li button {

  border-radius: 9px;
  width: 15px;
  height: 15px;
  cursor: pointer; /* 设置鼠标悬浮时为手形 */
  display: inline-block;
  background-color: white;
  border: none;
  color: #3f9dfe;
  transition: transform 0.3s ease, opacity 0.3s ease; /* 添加转换效果 */
  position: absolute;
  right: -10px; /* 初始位置在右侧外部 */
  opacity: 0; /* 开始时透明 */
  pointer-events: none; /* 禁用点击事件，直到显示 */
}

.nav-items li:hover {
  border-color: #3f9dfe;
  color: #3f9dfe;
  padding-left: 10px;
  padding-right: 30px; /* 为按钮预留空间 */
}

.nav-items li.active {
  border-color: #3f9dfe;
  color: #3f9dfe;
  padding-left: 20px;
  padding-right: 30px; /* 为按钮预留空间 */
}

.nav-items li:hover button,
.nav-items li.active button {
  transform: translateX(-19px); /* 移动到内部 */
  opacity: 1; /* 显示按钮 */
  pointer-events: auto; /* 激活点击事件 */
  transition: all 0.3s ease; /* 添加转换效果 */
}

.nav-items li:hover button:hover,
.nav-items li.active button:hover {
  color: #ffffff;
  background-color: #cbcbcb;
  font-weight: bold; /* 设置字体加粗 */
}

.current-route {
  font-size: 14px;
  color: #333;
}

.is-refresh,
.is-fullscreen{
  cursor: pointer; /* 设置鼠标悬浮时为手形 */
  transition: scale 0.3s ease;
  margin-right: 10px;
}

.is-refresh:hover,
.is-fullscreen:hover {
  scale: 1.25;
  color: #409eff; /* 或者其他你想要的颜色 */
}

.container {
  display: flex;
  /* 以下是一些可选的额外样式调整，根据需求添加 */
  justify-content: space-between; /* 元素在主轴（水平方向）均匀分布 */
  align-items: center; /* 元素在交叉轴（垂直方向）居中对齐 */
}

</style>
